import request from '../../services/request'

Page({
  data: {
    bookName: '',
    unitList: [],
    selectedUnit: '1',
    wordCount: 0,
    coverType: 'none', // none/cn/en
    filterList: [
      { label: '全部', value: 0 },
      { label: '未学', value: 1 },
      { label: '已学', value: 2 }
    ],
    filterIndex: [0],
    filterPickerVisible: false,
    wordList: [],
    allWordList: [], // 新增，保存全部单词
    isPlayingAudio: false, // 新增，控制播放状态
    playingIndex: -1, // 新增，记录正在播放的下标
    activeIndex: -1, // 新增，记录当前激活的卡片下标
    pronunciationMode: 'us', // 'us' 美音，'uk' 英音
    filterFormatter(item) {
      return item.label;
    }
  },

  onLoad(options) {
    const { bookId } = options
    if (!bookId) {
      wx.showToast({
        title: '参数错误',
        icon: 'error'
      })
      return
    }
    // 只请求一次
    this.loadBookData(bookId)
  },

  // 只请求一次，保存全部单词
  async loadBookData(bookId) {
    try {
      wx.showLoading({
        title: '加载中...',
        mask: true
      })
      const res = await request.get(`/book/getWordList?bookId=${bookId}`)
      wx.hideLoading()
      if (res.code === 200) {
        const { bookName, list } = res.data
        // 计算单元数（每20个单词一个单元）
        const unitCount = Math.ceil(list.length / 20)
        const unitList = Array.from({ length: unitCount }, (_, i) => ({
          unitId: (i + 1).toString(),
          unitName: `Unit ${i + 1}`
        }))
        wx.setNavigationBarTitle({ title: bookName })
        this.setData({
          bookName,
          unitList,
          wordCount: list.length,
          allWordList: list
        })
        // 默认加载第一个单元
        this.loadUnitWords(1)
      } else {
        wx.showToast({
          title: res.message || '加载失败',
          icon: 'error'
        })
      }
    } catch (error) {
      wx.hideLoading()
      console.error('加载词书失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'error'
      })
    }
  },

  // 只做本地分割
  loadUnitWords(unitId) {
    const allWordList = this.data.allWordList || []
    const startIndex = (unitId - 1) * 20
    const endIndex = Math.min(startIndex + 20, allWordList.length)
    const unitWords = allWordList.slice(startIndex, endIndex)
    // 处理单词数据
    const processedWords = unitWords.map(word => {
      const { headWord, content } = word
      const { word: wordContent } = content
      const { content: wordDetail } = wordContent
      const { trans, usphone, ukphone } = wordDetail
      // 展示所有词性和释义，词性后加点号
      let mean = ''
      if (Array.isArray(trans)) {
        mean = trans.map(t => `${t.pos ? t.pos + '.' : ''} ${t.tranCn || ''}`.trim()).join('；')
      }
      return {
        word: headWord,
        mean,
        showEn: false,
        showCn: false,
        phonetic: {
          us: usphone,
          uk: ukphone
        },
        sentences: wordDetail.sentence?.sentences || [],
        phrases: wordDetail.phrase?.phrases || [],
        synonyms: wordDetail.syno?.synos || []
      }
    })
    this.setData({
      wordList: processedWords
    })
  },

  onUnitChange(e) {
    const unitId = e.detail.value
    this.setData({ selectedUnit: unitId, activeIndex: -1 })
    // 只做本地分割
    this.loadUnitWords(unitId)
  },

  onCoverTab(e) {
    const type = e.currentTarget.dataset.type;
    // 切换遮盖时，重置所有单词的showEn/showCn
    const wordList = this.data.wordList.map(item => ({
      ...item,
      showEn: false,
      showCn: false
    }));
    this.setData({ coverType: type, wordList });
  },

  onFilterCellClick() {
    this.setData({ filterPickerVisible: true });
  },

  onFilterPickerChange(e) {
    this.setData({
      filterIndex: e.detail.value,
      filterPickerVisible: false
    });
    // TODO: 根据筛选条件过滤单词列表
  },

  onFilterPickerCancel() {
    this.setData({ filterPickerVisible: false });
  },

  onShowEn(e) {
    const idx = e.currentTarget.dataset.index;
    const wordList = this.data.wordList.slice();
    wordList[idx].showEn = true;
    this.setData({ wordList });
  },

  onShowCn(e) {
    const idx = e.currentTarget.dataset.index;
    const wordList = this.data.wordList.slice();
    wordList[idx].showCn = true;
    this.setData({ wordList });
  },

  onTogglePronunciationMode() {
    this.setData({
      pronunciationMode: this.data.pronunciationMode === 'us' ? 'uk' : 'us'
    })
  },

  onPlaySound(e) {
    // 如果点击的是 cover 区域（查看释义/单词），不激活也不播放
    if (e.target && e.target.dataset && e.target.dataset.cover == 1) {
      return;
    }
    if (this.data.isPlayingAudio) return;
    const idx = e.currentTarget.dataset.index;
    this.setData({ isPlayingAudio: true, playingIndex: idx, activeIndex: idx });
    const wordList = this.data.wordList;
    const item = wordList[idx];
    let audioKey = '';
    let type = 2;
    if (this.data.pronunciationMode === 'us') {
      if (item && item.usspeech) {
        audioKey = item.usspeech;
      } else if (item && item.word) {
        audioKey = item.word;
      }
      type = 2;
    } else {
      if (item && item.ukspeech) {
        audioKey = item.ukspeech;
      } else if (item && item.word) {
        audioKey = item.word;
      }
      type = 1;
    }
    if (!audioKey) {
      wx.showToast({ title: '无音频', icon: 'none' });
      this.setData({ isPlayingAudio: false, playingIndex: -1 });
      return;
    }
    const url = `https://dict.youdao.com/dictvoice?audio=${encodeURIComponent(audioKey)}&type=${type}`;
    const innerAudioContext = wx.createInnerAudioContext();
    innerAudioContext.src = url;
    innerAudioContext.play();
    innerAudioContext.onEnded(() => {
      innerAudioContext.destroy();
      this.setData({ isPlayingAudio: false, playingIndex: -1 });
    });
    innerAudioContext.onError(() => {
      wx.showToast({ title: '音频播放失败', icon: 'none' });
      innerAudioContext.destroy();
      this.setData({ isPlayingAudio: false, playingIndex: -1 });
    });
  },

  onStartLearn() {
    const wordList = this.data.wordList;
    const activeIndex = typeof this.data.activeIndex === 'number' ? this.data.activeIndex : 0;
    wx.navigateTo({
      url: '/pages/worddetail/worddetail',
      success: function(res) {
        res.eventChannel.emit('acceptUnitWords', { wordList, activeIndex });
      }
    });
  }
}); 